const axios = require("axios");

const cancelMap = new Map();

/**
 * 取消全部请求
 */
function cancelAll() {
  cancelMap.forEach((source) => source.cancel());
  cancelMap.clear();
}

/**
 * 设置取消请求的token
 * @param axiosInstance
 */
function setCancelToken(axiosInstance) {
  axiosInstance.interceptors.request.use((config) => {
    const source = axios.CancelToken.source();
    if (!config.cancelToken && !config.cancelIgnore) {
      config.cancelToken = source.token;
      cancelMap.set(source.token, source);
    }
    return config;
  });
  // 请求结束，删除保存的token
  axiosInstance.interceptors.response.use((response) => {
    const { config } = response;
    if (config.url.indexOf("qrbdusslogin") > -1) {
      const cookie = convertToCookieFormat(response.headers["set-cookie"]);
      response.data = {
        data: response.data,
        cookie: cookie,
        now: Date.now(),
      };
    }
    if (config.cancelToken) {
      cancelMap.delete(config.cancelToken);
    }
    // console.log(response)

    return response;
  });
}

function convertToCookieFormat(cookiesArray) {
  // 定义一个空字符串来存储最终的结果
  let cookieString = "";

  // 遍历cookiesArray中的每一个元素
  cookiesArray.forEach((cookie) => {
    // 分割字符串以获取键值对
    const keyValuePairs = cookie.split("; ");

    // 遍历每一对键值
    keyValuePairs.forEach((pair) => {
      // 去除Max-Age, Path, Expires, Secure, SameSite等属性，只保留键值对
      if (pair.includes("=")) {
        const [key, value] = pair.split("=");
        // 如果是键值对，则添加到结果字符串中
        if (
          ![
            "max-age",
            "path",
            "expires",
            "secure",
            "sameSite",
            "domain",
          ].includes(key.toLowerCase())
        ) {
          cookieString += `${key}=${value}; `;
        }
      }
    });
  });

  // 移除最后一个多余的分号和空格
  cookieString = cookieString.trim().replace(/; $/, "");

  return cookieString;
}

function createAxios(config) {
  const axiosInstance = axios.create({ ...config });
  setCancelToken(axiosInstance);
  return axiosInstance;
}

module.exports = {
  cancelAll,
  createAxios,
};
